package com.example.choupaiapp.main.activity.mine;

import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.activity.message.ByIdDetailActivity;
import com.example.choupaiapp.main.bean.MineCommentBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.gcssloop.widget.RCImageView;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by ASUS on 2019/11/25.
 */

public class MineCommentActivity extends CommonActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.empty_img)
    ImageView empty_img;
    private int pageNum = 1;
    private int pageSize = 10;
    private QuickAdapter<MineCommentBean.PageBean.ListBean> quickAdapter;
    private UserInfoBean mUserInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_comment);
    }

    @Override
    protected void initView() {
        setTitle("我评论的");

        EventBus.getDefault().register(this);

        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
        refreshLayout.setEnableAutoLoadMore(true);

        mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");

        quickAdapter = new QuickAdapter<MineCommentBean.PageBean.ListBean>(context, R.layout.item_mine_comment) {
            @Override
            protected void convert(BaseAdapterHelper helper, MineCommentBean.PageBean.ListBean item) {
                CircleImageView head_photo = helper.getView(R.id.head_photo);
                Glide.with(context)
                        .load(mUserInfoBean.getUser().getAvatar() + Config.IMAGE_LIM)
                        .dontAnimate()
                        .placeholder(R.mipmap.icon_no_head)
                        .into(head_photo);

                head_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                });

                helper.setText(R.id.name, mUserInfoBean.getUser().getNickname());

                ImageView praise_iv = helper.getView(R.id.praise_iv);
                if (item.getIsLike() == 1) {
                    praise_iv.setImageResource(R.mipmap.icon_praise_select);
                } else {
                    praise_iv.setImageResource(R.mipmap.item_praise);
                }
                helper.getView(R.id.praise_ll).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isDoubleClick()) {
                            return;
                        }
                        if (item.getIsLike() == 1) {
                            showDialog(context, "取消中...");
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("contentId", item.getId());
                                jsonObject.put("module", 1);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CANCEL_PRAISE_HOME, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                @Override
                                public void onSuccess(SendCodeBean sendCodeBean) {
                                    dismissDialog();
                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
//                                        item.setIsLike(0);
//                                        quickAdapter.notifyDataSetChanged();
                                        pageNum=1;
                                        initData();
                                        EventBus.getDefault().post("refresh_home_follow");
                                        EventBus.getDefault().post("refresh_mine");
                                    } else {
                                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                        }else{
                                            showImageToas(sendCodeBean.getMsg());
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    dismissDialog();
                                }
                            });
                        } else {
                            showDialog(context, "点赞中...");
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("contentId", item.getId());
                                jsonObject.put("module", 1);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.PRAISE_HOME, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                @Override
                                public void onSuccess(SendCodeBean sendCodeBean) {
                                    dismissDialog();
                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                        pageNum=1;
                                        initData();
                                        EventBus.getDefault().post("refresh_home_follow");
                                        EventBus.getDefault().post("refresh_mine");
                                    } else {
                                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                        }else{
                                            showImageToas(sendCodeBean.getMsg());
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    dismissDialog();
                                }
                            });
                        }
                    }
                });

                helper.setText(R.id.praise_num, item.getLikeSum() + "");
                helper.setText(R.id.comment_num, item.getCommentSum() + "");
                helper.setText(R.id.title, item.getTitle());

                if (item.getAnonymity() == 1) {
                    helper.setText(R.id.other_name, "匿名用户");
                } else {
                    helper.setText(R.id.other_name, item.getNickname());
                }

                RCImageView photo = helper.getView(R.id.photo);

                if (item.getType() == 1) {
                    Glide.with(context)
                            .load(item.getUrls() + "?vframe/jpg/offset/1")
                            .dontAnimate()
                            .into(photo);
                } else if (item.getType() == 2) {
                    Glide.with(context)
                            .load(item.getUrls().split("\\|")[0] + Config.IMAGE_LIM)
                            .crossFade()
                            .error(R.color.color_f3f3)
                            .into(photo);
                } else if (item.getType() == 3) {
                    Glide.with(context)
                            .load(R.color.color_f3f3)
                            .crossFade()
                            .error(R.color.color_f3f3)
                            .into(photo);
                }

                TextView comment = helper.getView(R.id.comment);
                if (!TextUtils.isEmpty(item.getReplyNickname())) {
                    if(item.getNickname().equals(item.getReplyNickname())){
                        if(item.getAnonymity()==1){
                            SpannableString content = new SpannableString("回复了" + "匿名用户" + ":" + item.getComment());
                            StyleSpan span = new StyleSpan(Typeface.BOLD);
                            content.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            comment.setText(content);
                        }else{
                            SpannableString content = new SpannableString("回复了" + item.getReplyNickname() + ":" + item.getComment());
                            StyleSpan span = new StyleSpan(Typeface.BOLD);
                            content.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            comment.setText(content);
                        }
                    }else{
                        SpannableString content = new SpannableString("回复了" + item.getReplyNickname() + ":" + item.getComment());
                        StyleSpan span = new StyleSpan(Typeface.BOLD);
                        content.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        comment.setText(content);
                    }
                } else {
                    if (item.getAnonymity() == 1) {
                        SpannableString content = new SpannableString("回复了" + "匿名用户" + ":" + item.getComment());
                        StyleSpan span = new StyleSpan(Typeface.BOLD);
                        content.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        comment.setText(content);
                    } else {
                        SpannableString content = new SpannableString("回复了" + item.getNickname() + ":" + item.getComment());
                        StyleSpan span = new StyleSpan(Typeface.BOLD);
                        content.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        comment.setText(content);
                    }

                }
            }
        };

        listview.setAdapter(quickAdapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                Bundle bundle1 = new Bundle();
                bundle1.putString("id", quickAdapter.getItem(i).getId() + "");
                startActivity(ByIdDetailActivity.class, bundle1);
            }
        });
    }

    @Override
    protected void initData() {
        showDialog(context, null);
        HttpParams params = new HttpParams();
        params.put("limit", pageSize);
        params.put("page", pageNum++);
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.MINE_COMMENT, params, Url.MINE_COMMENT, new Callback<MineCommentBean>() {
            @Override
            public void onSuccess(MineCommentBean mineVideoListBean) {
                dismissDialog();
                if (mineVideoListBean.getCode() == Contacts.SUCCESS) {
                    if (pageNum - 1 == 1) {
                        if (mineVideoListBean.getPage().getList() != null && mineVideoListBean.getPage().getList().size() == 0) {
                            empty_img.setVisibility(View.VISIBLE);
                            empty_img.setImageResource(R.mipmap.icon_coment_empty);
                        } else {
                            empty_img.setVisibility(View.GONE);
                        }
                        quickAdapter.clear();
                        quickAdapter.addAll(mineVideoListBean.getPage().getList());
                    } else {
                        quickAdapter.addAll(mineVideoListBean.getPage().getList());
                    }

                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    quickAdapter.notifyDataSetChanged();

                    int pagecount;
                    if (mineVideoListBean.getPage().getTotalCount() % pageSize == 0) {
                        pagecount = mineVideoListBean.getPage().getTotalCount() / pageSize;
                    } else {
                        pagecount = mineVideoListBean.getPage().getTotalCount() / pageSize + 1;
                    }

                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }

                } else {
                    if (pageNum - 1 == 1) {
                        empty_img.setVisibility(View.VISIBLE);
                        empty_img.setImageResource(R.mipmap.icon_no_net);
                    }
                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    if (mineVideoListBean.getCode() == Contacts.TOKEN_EMPTY) {
                    }else{
                        showImageToas(mineVideoListBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
                dismissDialog();
                refreshLayout.finishRefresh();
                refreshLayout.finishLoadMore();
                if (pageNum - 1 == 1) {
                    empty_img.setVisibility(View.VISIBLE);
                    empty_img.setImageResource(R.mipmap.icon_no_net);
                }

            }
        });

    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.contains("refresh_follow_search")) {
            quickAdapter.getItem(Integer.parseInt(event.split(":")[2])).setIsAttention(1);
            quickAdapter.notifyDataSetChanged();
        } else if (event.contains("refresh_praise_search")) {
            quickAdapter.getItem(Integer.parseInt(event.split(":")[2])).setLikeSum(quickAdapter.getItem(Integer.parseInt(event.split(":")[2])).getLikeSum() + 1);
            quickAdapter.getItem(Integer.parseInt(event.split(":")[2])).setIsLike(1);
            quickAdapter.notifyDataSetChanged();
        } else if (event.contains("refresh_cancel_praise_search")) {
            quickAdapter.remove(Integer.parseInt(event.split(":")[2]));
            quickAdapter.notifyDataSetChanged();
        } else if (event.equals("refresh_comment_mine")) {
            pageNum = 1;
            initData();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        initData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        initData();
    }
}
